package com.neshai.webapp.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class JwtUtil {
    private static final String secret = "jweflsdajfojk@0oijfsa92nnlsadf01290@klmaflkjlknvkalkojllk";

    public static String generateToken(int id,String email,String walletAddress) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        claims.put("email",email);
        claims.put("wallet_address",walletAddress);
        return createToken(claims, String.valueOf(id));
    }

    public static String createToken(Map<String, Object> claims, String subject) {
        // 1 hour 3600000L  10s 10000  1d 3600000*24=86400000   1month=86400000*30 =2592000000L
        long jwtExpirationInMs = 2592000000L;
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationInMs))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    public static Boolean validateToken(String token, String id) {
        final String extractedSubject = extractSubject(token);
        return (extractedSubject.equals(id) && !isTokenExpired(token));
    }

    public static String extractSubject(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public static Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public static  <T> T extractClaim(String token, java.util.function.Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    public static Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public static Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }
}
